package com.adtec.base.cloud.wechatservice.wechatcloud.wechat.service.impl;

import com.adtec.base.cloud.commons.exception.CustomException;
import com.adtec.base.cloud.commons.exception.CustomExceptionType;
import com.adtec.base.cloud.commons.utils.HttpRequestUtil;
import com.adtec.base.cloud.wechatservice.wechatcloud.config.DbLoadSysConfig;
import com.adtec.base.cloud.wechatservice.wechatcloud.wechat.model.message.Msgid;
import com.adtec.base.cloud.wechatservice.wechatcloud.wechat.model.message.Text;
import com.adtec.base.cloud.wechatservice.wechatcloud.wechat.model.message.WeChatMessageRsult;
import com.adtec.base.cloud.wechatservice.wechatcloud.wechat.model.message.WeChatTextMessage;
import com.adtec.base.cloud.wechatservice.wechatcloud.wechat.model.recallMessage.RecallMessageModel;
import com.adtec.base.cloud.wechatservice.wechatcloud.wechat.model.token.WeChatToken;
import com.adtec.base.cloud.wechatservice.wechatcloud.wechat.service.EnterpriseWeChatService;
import com.adtec.base.cloud.security.jwt.utils.GetUserId;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 86185
 */
@Component
@Slf4j
public class EnterpriseWeChatServiceImpl implements EnterpriseWeChatService {

    @Resource
    private GetUserId getUserId;

    @Resource
    private DbLoadSysConfig dbLoadSysConfig;
    @Resource
    private HttpRequestUtil httpRequestUtil;

    @Override
    public String sendInfo(Integer appId,
                           String touser,
                           String toparty,
                           String totag,
                           String info) {
        String usernameFromHeader = getUserId.getUsernameFromHeader();
        log.info("发送文本消息操作者" + usernameFromHeader);
        this.refreshDbLoadSysConfig();//刷新配置这里必须自带
        WeChatMessageRsult weChatMessageRsult = this.sendTextMessageByApp(appId, info, touser, toparty, totag);
        log.info(String.valueOf(weChatMessageRsult));
        if (weChatMessageRsult.getErrcode() == 0) {
            return weChatMessageRsult.getMsgid();
        } else {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "信息发送失败");
        }
    }

    @Override
    public String recallMessage(String msgid) {
        String usernameFromHeader = getUserId.getUsernameFromHeader();
        log.info("撤回消息操作者" + usernameFromHeader);
        this.refreshDbLoadSysConfig();//刷新配置这里必须自带
        RecallMessageModel recallMessageModel = this.recallMessageByApp(msgid);
        log.info(String.valueOf(recallMessageModel));
        if (recallMessageModel.getErrcode() == 0) {
            return "撤回成功";
        } else {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "撤回失败,请联系管理员");
        }
    }


    //撤回消息
    private RecallMessageModel recallMessageByApp(String msgid) {
        Msgid msgidModel = new Msgid();
        msgidModel.setMsgid(msgid);
        String jsonStr = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            jsonStr = mapper.writeValueAsString(msgidModel);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String url = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.recall");
        String urlTemplate = UriComponentsBuilder.fromHttpUrl(url).queryParam("access_token", "{access_token}").encode().toUriString();
        String corpsecret = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.testsecret");
        String access_token = this.getToken(corpsecret);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", access_token);
        Object request = httpRequestUtil.postParamsJsonRequest(urlTemplate, jsonStr, params);
        RecallMessageModel recallMessageModel = new RecallMessageModel();
        ObjectMapper objMapper = new ObjectMapper();
        try {
            String objjsonStr = objMapper.writeValueAsString(request);
            recallMessageModel = JSON.parseObject(objjsonStr, new TypeReference<RecallMessageModel>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return recallMessageModel;
    }

    //发送文本信息
    private WeChatMessageRsult sendTextMessageByApp(Integer appId, String info, String touser, String toparty, String totag) {
        WeChatTextMessage weChatMessage = new WeChatTextMessage();
        weChatMessage.setTouser(touser);
        weChatMessage.setToparty(toparty);
        weChatMessage.setTotag(totag);
        weChatMessage.setAgentid(appId);
        Text text = new Text();
        text.setContent(info);
        weChatMessage.setText(text);
        String jsonStr = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            jsonStr = mapper.writeValueAsString(weChatMessage);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String url = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.send");
        String urlTemplate = UriComponentsBuilder.fromHttpUrl(url).queryParam("access_token", "{access_token}").encode().toUriString();
        String corpsecret = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.testsecret");
        String access_token = this.getToken(corpsecret);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", access_token);
        Object request = httpRequestUtil.postParamsJsonRequest(urlTemplate, jsonStr, params);

        WeChatMessageRsult weChatMessageRsult = new WeChatMessageRsult();
        ObjectMapper objMapper = new ObjectMapper();
        try {
            String objjsonStr = objMapper.writeValueAsString(request);
            weChatMessageRsult = JSON.parseObject(objjsonStr, new TypeReference<WeChatMessageRsult>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return weChatMessageRsult;
    }

    //根据用户ID获取用户信息
    private Object getUserInfoByUserid(String userid) {
        String url = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.get");
        String urlTemplate = UriComponentsBuilder.fromHttpUrl(url).queryParam("access_token", "{access_token}").queryParam("userid", "{userid}").encode().toUriString();
        String corpsecret = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.txltbsecret");
        String access_token = this.getToken(corpsecret);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", access_token);
        params.put("userid", userid);
        Object request = httpRequestUtil.getParamsRequest(urlTemplate, params);
        return request;
    }

    //获取企业微信token,需要根据不同appid的secret来获取
    private String getToken(String corpsecret) {
        //从参数配置中获取对象
        String url = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.gettoken");
        String corpid = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.corpid");
//        String corpsecret = dbLoadSysConfig.getConfigItem("Enterprise.WeChat.corpsecret");
        String urlTemplate = UriComponentsBuilder.fromHttpUrl(url).queryParam("corpid", "{corpid}").queryParam("corpsecret", "{corpsecret}").encode().toUriString();
        Map<String, String> params = new HashMap<>();
        params.put("corpid", corpid);
        params.put("corpsecret", corpsecret);
        Object request = httpRequestUtil.getParamsRequest(urlTemplate, params);
        //解析获取的token
        WeChatToken weChatToken = new WeChatToken();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonStr = mapper.writeValueAsString(request);
            weChatToken = JSON.parseObject(jsonStr, new TypeReference<WeChatToken>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String token = "";
        if (weChatToken.getErrcode().equalsIgnoreCase("0")) {
            token = weChatToken.getAccess_token();
        } else {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "企业微信获取token失败,请检查!信息如下:" + weChatToken);
        }
        return token;
    }

    //    刷新内存配置
    private void refreshDbLoadSysConfig() {
        try {
            log.info("刷新内存配置");
            dbLoadSysConfig.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
